package com.hrt.datasender.datacollect.drive.weigeng;

import java.util.HashMap;

import com.hrt.datasender.datacollect.drive.DriveConfigModel;
import com.hrt.datasender.datacollect.drive.DriveTimer;
import com.hrt.datasender.datadao.model.BcDevicesModel;

public class WeiGengDataAsker extends DriveTimer {
    
    private final int msgLength = 64;
    
    private static final int SHIFTBIT16 = 16;
    
    private static final int SHIFTBIT8 = 8;
    
    private static final int MASKCODEFFFF = 0xffff;
    
    private static final int MASKCODEFF = 0xff;
    
    private final int heartBreakInterval = 30;

    private byte[] askMsg = null;
    private WeiGengSocketClient socket = null;

    @Override
    public void executeTimer(DriveConfigModel configs, BcDevicesModel deviceData) {
        if (initWG(configs)) {
            socket.writeMsg(askMsg);
        }
    }

    /**
     * 
     * @return 如果是第一次初始化，返回false
     */
    private boolean initWG(DriveConfigModel deviceConfigs) {
        if (socket == null) {

            HashMap<String, String> configs = deviceConfigs.getConfig();

            String ip = configs.get("ip");
            Integer port = Integer.parseInt(configs.get("port"));
            Integer controlNo = Integer.parseInt(configs.get("controlNo"));

            socket = new WeiGengSocketClient(ip, port, heartBreakInterval);
            socket.startNetty();

            byte[] controlNoByte = converIntTo0X(controlNo);
            
            final int askMsgByteAddr3 = 3;
            final int askMsgByteAddr4 = 4;
            final int askMsgByteAddr5 = 5;
            final int askMsgByteAddr6 = 6;
            final int askMsgByteAddr7 = 7;
            final int askMsgStart = 0X17;
            final int askMsgFuntion = 0X20;
            final int controlNoByteAddr3 = 3;
            
            askMsg = new byte[msgLength];
            askMsg[0] = askMsgStart;
            askMsg[1] = askMsgFuntion;
            askMsg[2] = 0;
            askMsg[askMsgByteAddr3] = 0;
            askMsg[askMsgByteAddr4] = controlNoByte[0];
            askMsg[askMsgByteAddr5] = controlNoByte[1];
            askMsg[askMsgByteAddr6] = controlNoByte[2];
            askMsg[askMsgByteAddr7] = controlNoByte[controlNoByteAddr3];

            return false;
        }
        return true;
    }

    private static byte[] converIntTo0X(int value) {

        int high1 = (MASKCODEFFFF & (value >> SHIFTBIT16));
        int low1 = (MASKCODEFFFF & value);

        byte h1h = (byte) (MASKCODEFF & (high1 >> SHIFTBIT8));
        byte h1l = (byte) (MASKCODEFF & high1);

        byte l1h = (byte) (MASKCODEFF & (low1 >> SHIFTBIT8));
        byte l1l = (byte) (MASKCODEFF & low1);

        byte[] result = new byte[] { l1l, l1h, h1l, h1h };

        return result;
    }

}
